package com.pet.controller;

import com.pet.dto.AdminDto;
import com.pet.pojo.Admin;
import com.pet.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("login")
    public Map login(AdminDto adminDto, HttpSession session){

        HashMap<String, Object> map = new HashMap<>();

        //判断
        if(adminDto!=null && adminDto.getUsername()!=null && adminDto.getPassword()!=null){
            //判断验证码
            if(session.getAttribute("code").toString().equals(adminDto.getCaptcha())){
                //判断用户名和密码，查询数据库
                Admin db_admin =  adminService.login(adminDto.getUsername(),adminDto.getPassword());
                System.out.println(db_admin);
                //判断
                if(db_admin != null ){
                    //登录成功
                    session.setAttribute("admin",db_admin);

                    map.put("code",200);
                    map.put("msg","success");
                    map.put("data",db_admin);

                }else{

                    map.put("code",-1);
                    map.put("msg","fail");
                }

            }else{
                map.put("code",-1);
                map.put("msg","fail");
            }

        }else{
            map.put("code",-1);
            map.put("msg","fail");
        }

        return map;
    }


    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {

        //需要删除session中存储的admin
        //request.getSession().removeAttribute("admin");//移除session中的属性
        request.getSession().invalidate();//销毁session

        response.sendRedirect(request.getContextPath()+"/index.html");
    }



}
